package com.cfweb.util;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.ws.rs.core.MediaType;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpRequestBase;

import com.cfweb.controller.LoginHandler;
import com.cfweb.exception.CloudFoundryApiException;
import com.cfweb.pojo.OauthToken;

/**
 * @author lmx
 *
 */
public class CloudFoundryClientUtil {
	
	public static void setAccessHeaders(HttpRequestBase method,HttpSession session) throws Exception{
		OauthToken token = (OauthToken)session.getAttribute(LoginHandler.TOKEN);
		method.addHeader(HttpHeaders.AUTHORIZATION, token.getTokenType()+" "+token.getToken(session));
		method.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
		method.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
	}
	
	public static void setUuaHeaders(HttpRequestBase method,HttpSession session) throws Exception{
		OauthToken token = (OauthToken)session.getAttribute(LoginHandler.TOKEN);
		method.addHeader(HttpHeaders.AUTHORIZATION, token.getTokenType()+" "+token.getToken(session));
		method.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
		method.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
	}
	
	private static Map<String, String> buildCcAccessHeaderParams(HttpSession session) throws Exception{
		Map<String, String> results=new HashMap<String, String>();
		OauthToken token = (OauthToken)session.getAttribute(LoginHandler.TOKEN);
		results.put(HttpHeaders.AUTHORIZATION, token.getTokenType()+" "+token.getToken(session));
		results.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
		results.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
		return results;
	}
	
	private static Map<String, String> buildUaaAccessHeaderParams(HttpSession session) throws Exception{
		Map<String, String> results=new HashMap<String, String>();
		//String host = ((URL)session.getAttribute(LoginHandler.TARGET)).toString();
		OauthToken token = (OauthToken)session.getAttribute(LoginHandler.TOKEN);
//		OauthToken token=OauthApi.login("admin", "c1oudc0w",null);
		//host=host.replaceFirst(host.substring(0, host.indexOf(".")), "uaa");
		//results.put(HttpHeaders.HOST,host.substring(7));
		results.put(HttpHeaders.AUTHORIZATION, token.getTokenType()+" "+token.getToken(session));
		results.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
		results.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
		return results;
	}
	
	public static String doOauth(String url,Map<String,String> params,HttpSession session) throws Exception{
		Base64 base64=new Base64();
		Map<String,String> headers=new HashMap<String,String>();
		String host = ((URL)session.getAttribute(LoginHandler.TARGET)).toString();
		host=host.replaceFirst(host.substring(0, host.indexOf(".")), "uaa");
		headers.put(HttpHeaders.HOST,host);
		headers.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
		headers.put(
				"Authorization",
				String.format(
						"Basic %s",
						new String(base64.encode(String.format("%s:%s","cf",
								"").getBytes("UTF-8")), "UTF-8")));
		
		HttpClientResponse response=HttpClientUtil.doPost(url, params, headers,false);
		if (!HttpStatusUtil.isSuccessStatus(response.getStatus())){ 
			String content = response.getBody();
			Map<String, Object> data = JsonUtil.convertJsonToMap(content);
			throw new CloudFoundryApiException(Integer.valueOf(response.getStatus()),(String)data.get("error_description"));
		}
		 return response.getBody();
	}
	
	public static String doUaaPost(String url,Map<String,Object> params,HttpSession session) throws Exception{
		Map<String,String> headers=buildUaaAccessHeaderParams(session);
		HttpClientResponse response=HttpClientUtil.doPostWithJsonType(url, params, headers,false);
		if (!HttpStatusUtil.isSuccessStatus(response.getStatus())){ 
			String content = response.getBody();
			Map<String, Object> data = JsonUtil.convertJsonToMap(content);
			throw new CloudFoundryApiException(Integer.valueOf(response.getStatus()),(String)data.get("message"));
		}
		 return response.getBody();
	}
	
	public static String doUaaPut(String url,Map<String,Object> params,HttpSession session) throws Exception{
		Map<String,String> headers=buildUaaAccessHeaderParams(session);
		HttpClientResponse response=HttpClientUtil.doPut(url, params, headers, false);
		if (!HttpStatusUtil.isSuccessStatus(response.getStatus())){ 
			String content = response.getBody();
			Map<String, Object> data = JsonUtil.convertJsonToMap(content);
			throw new CloudFoundryApiException(Integer.valueOf(response.getStatus()),(String)data.get("message"));
		}
		 return response.getBody();
	}
	
	public static String doUaaGet(String url,Map<String,String> params,HttpSession session) throws Exception{
		Map<String,String> headers=buildUaaAccessHeaderParams(session);
		HttpClientResponse response=HttpClientUtil.doGet(url, params, headers,false);
		if (!HttpStatusUtil.isSuccessStatus(response.getStatus())){ 
			String content = response.getBody();
			Map<String, Object> data = JsonUtil.convertJsonToMap(content);
			throw new CloudFoundryApiException(Integer.valueOf(response.getStatus()),(String)data.get("message"));
		}
		 return response.getBody();
	}
	
	public static String doCCGet(String url,Map<String,String> params,HttpSession session) throws Exception{
		Map<String,String> headers=buildCcAccessHeaderParams(session);
		HttpClientResponse response=HttpClientUtil.doGet(url, params, headers,false);
		if (!HttpStatusUtil.isSuccessStatus(response.getStatus())){ 
			String content = response.getBody();
			Map<String, Object> data = JsonUtil.convertJsonToMap(content);
			if(data.get("error")!=null){
				throw new CloudFoundryApiException(Integer.valueOf(response.getStatus()),(String)data.get("error"));
			}
			throw new CloudFoundryApiException(Integer.valueOf(response.getStatus()),(String)data.get("description"));
		}
		 return response.getBody();
	}
	
	public static String doCCPost(String url,Map<String,Object> params,HttpSession session) throws Exception{
		Map<String,String> headers=buildCcAccessHeaderParams(session);
		HttpClientResponse response=HttpClientUtil.doPostWithJsonType(url, params, headers,false);
		if (!HttpStatusUtil.isSuccessStatus(response.getStatus())){ 
			String content = response.getBody();
			Map<String, Object> data = JsonUtil.convertJsonToMap(content);
			throw new CloudFoundryApiException(Integer.valueOf(response.getStatus()),(String)data.get("description"));
		}
		 return response.getBody();
	}
	
	public static String doCCPut(String url,Map<String,Object> params,HttpSession session) throws Exception{
		Map<String,String> headers=buildCcAccessHeaderParams(session);
		HttpClientResponse response=HttpClientUtil.doPut(url, params, headers,false);
		if (!HttpStatusUtil.isSuccessStatus(response.getStatus())){ 
			String content = response.getBody();
			Map<String, Object> data = JsonUtil.convertJsonToMap(content);
			throw new CloudFoundryApiException(Integer.valueOf(response.getStatus()),(String)data.get("description"));
		}
		 return response.getBody();
	}
	
	public static String doResouceMatch(String url,Map<String,Object> params,HttpSession session) throws Exception{
		Map<String,String> headers=buildCcAccessHeaderParams(session);
		HttpClientResponse response=HttpClientUtil.doResouceMatchPut(url, params, headers,false);
		if (!HttpStatusUtil.isSuccessStatus(response.getStatus())){ 
			String content = response.getBody();
			Map<String, Object> data = JsonUtil.convertJsonToMap(content);
			throw new CloudFoundryApiException(Integer.valueOf(response.getStatus()),(String)data.get("description"));
		}
		 return response.getBody();
	}
	
	
	public static String doCCDelete(String url,Map<String,Object> params,HttpSession session) throws Exception{
		Map<String,String> headers=buildCcAccessHeaderParams(session);
		HttpClientResponse response=HttpClientUtil.doDelete(url, params, headers,false);
		if (!HttpStatusUtil.isSuccessStatus(response.getStatus())){ 
			String content = response.getBody();
			Map<String, Object> data = JsonUtil.convertJsonToMap(content);
			throw new CloudFoundryApiException(Integer.valueOf(response.getStatus()),(String)data.get("description"));
		}
		 return response.getBody();
	}
	
	public static String doCCPputWithFile(String url,Map<String,Object> params,HttpSession session) throws Exception{
		Map<String,String> headers=buildCcAccessHeaderParams(session);
		headers.remove(HttpHeaders.CONTENT_TYPE);
		HttpClientResponse response=HttpClientUtil.doPutWithFile(url, params, headers,false);
		if (!HttpStatusUtil.isSuccessStatus(response.getStatus())){ 
			String content = response.getBody();
			Map<String, Object> data = JsonUtil.convertJsonToMap(content);
			throw new CloudFoundryApiException(Integer.valueOf(response.getStatus()),(String)data.get("description"));
		}
		 return response.getBody();
	}
	
}
